package com.morty.config.interceptor;

import com.morty.base.consts.TraceConsts;
import com.morty.config.utils.ThreadContextHolder;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Log4j2
@Configuration
public class FeignHeaderInfoRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes == null) return;
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                log.debug("header: "+name + " = " + values);
                requestTemplate.header(name, values);
            }
        }
        if(ThreadContextHolder.getTraceId() != null){
            requestTemplate.header(TraceConsts.HTTP_HEADER_TRACE_ID, ThreadContextHolder.getTraceId());
        }
    }
}
